import mockjs from 'mockjs';
import {parse} from 'url';
// import { delay } from 'roadhog-api-doc';

let tableListDataSource = [];

function getRule(req, res, u) {
  let url = u;
  if (!url || Object.prototype.toString.call(url) !== '[object String]') {
    // eslint-disable-next-line prefer-destructuring
    url = req.url;
  }

  const params = parse(url, true).query;
  let dataSource = tableListDataSource;

  if (params.sorter) {
    const s = params.sorter.split('_');
    dataSource = dataSource.sort((prev, next) => {
      if (s[1] === 'descend') {
        return next[s[0]] - prev[s[0]];
      }

      return prev[s[0]] - next[s[0]];
    });
  }

  if (params.status) {
    const status = params.status.split(',');
    let filterDataSource = [];
    status.forEach(s => {
      filterDataSource = filterDataSource.concat(
        dataSource.filter(item => {
          if (parseInt(`${item.status}`, 10) === parseInt(s.split('')[0], 10)) {
            return true;
          }

          return false;
        }),
      );
    });
    dataSource = filterDataSource;
  }

  if (params.name) {
    dataSource = dataSource.filter(data => data.name.indexOf(params.name) > -1);
  }

  let pageSize = 10;
  if (params.pageSize) {
    pageSize = parseInt(`${params.pageSize}`, 0);
  }

//   todo kim-stamp 后端返回分页的规范格式
//   result: {
//            list: dataSource,  
//            pagination: {
//            total: dataSource.length,
//            pageSize,
//            current: parseInt(`${params.currentPage}`, 10) || 1,
//     },
// }

  const result = {
    code: 0,
    msg: '',
    content: mockjs.mock(
      {
        'list|666': [
          {
            'id|+1': 1,
            'status1|1': [1],
            'status2|1': [1, 2],
            'status3|1': [0, 1, 2],
            'status4|1': [1, 2, 3, 4],
            'status5|1': [1, 2, 3, 4, 5],
            'status6|1': [1, 2, 3, 4, 5, 6],
            'hobby|1': [1, 2, 3, 4, 5, 7, 8],
            order_sn: 'T@natural(100000,999999)',
            'bike_sn|+1': 800125445,
            user_id: '@natural(200000,900000)',
            user_name: '@cname',
            mobile: '17231813621',
            distance:'@natural(2000,9000)' ,
            total_time: '@natural(1000,9000)' ,
            start_time: '1972-08-13 00:57:12',
            end_time: '1990-09-23 12:41:40',
            total_fee: '@natural(1000,9000)' ,
            user_pay: '@natural(100,900)' ,
            'isMarried|2': true,
            address: '@city(true)',
            birthday: '@datetime',
            time: '@time',
          },

        ],
        pagination: {
          total: 666,
          pageSize: pageSize,
          current: parseInt(`${params.current}`, 10) || 1,
        },
      }
    ),
  }

  return res.json(result);
}


export default {
  'GET /api/search/list': getRule,
  // 'GET /api/search/list': apiCommon,
}


// export default delay(proxy, 1000); // 调用 delay 函数，统一处理
